const mysql = require('mysql');
const config = require('./config') || {};

// 数据库连接配置
const dbConfig = {
  host: config.database?.host || 'localhost',
  user: config.database?.user || 'root',
  password: config.database?.password || '123456zxy',
  database: config.database?.database || 'firstproject',
  port: config.database?.port || 3306,
  connectionLimit: 10,
  acquireTimeout: 60000,
  timeout: 60000,
  waitForConnections: true,
  queueLimit: 0,
  dateStrings: ['DATE', 'DATETIME', 'TIMESTAMP']
};

const db = mysql.createPool(dbConfig);

// 连接池错误处理
db.on('error', (err) => {
  console.error('Database pool error:', err.message);
  // 尝试自动重连
  if (err.code === 'PROTOCOL_CONNECTION_LOST') {
    console.log('Attempting to reconnect...');
    // 连接池会自动处理重连
  }
});

// 测试数据库连接
function testConnection() {
  return new Promise((resolve, reject) => {
    db.getConnection((err, connection) => {
      if (err) {
        console.error('Database connection failed:', err.message);
        reject(err);
      } else {
        console.log('Database connected successfully');
        connection.release();
        resolve();
      }
    });
  });
}

// 智能查询方法，同时支持回调风格和Promise风格
function smartQuery(sql, params, callback) {
  // 如果没有提供回调函数，返回Promise
  if (typeof callback !== 'function') {
    if (typeof params === 'function') {
      return promiseQuery(sql, []);
    }
    return promiseQuery(sql, params || []);
  }
  
  // 回调风格处理
  if (typeof params === 'function') {
    callback = params;
    params = [];
  }
  
  db.query(sql, params || [], (err, results) => {
    if (err) {
      console.error('Database query error:', err.message);
      return callback(err, null);
    }
    callback(null, results);
  });
}

// Promise风格的查询方法
function promiseQuery(sql, params = []) {
  return new Promise((resolve, reject) => {
    db.query(sql, params, (err, results) => {
      if (err) {
        console.error('Database query error:', err.message);
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
}

// 导出方法和连接池
module.exports = {
  pool: db,
  query: smartQuery,  // 默认导出智能查询方法，同时支持回调和Promise
  promiseQuery,       // 显式导出Promise风格的查询
  testConnection
};

// 确保兼容现有代码的调用方式
module.exports.query = smartQuery;
// 导出原始连接池以兼容现有代码
module.exports.getConnection = db.getConnection.bind(db);
module.exports.releaseConnection = db.releaseConnection?.bind(db);